package com.thwj.project.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thwj.common.annotation.Log;
import com.thwj.common.core.controller.BaseController;
import com.thwj.common.core.domain.AjaxResult;
import com.thwj.common.core.page.TableDataInfo;
import com.thwj.common.enums.BusinessType;
import com.thwj.common.exception.ServiceException;
import com.thwj.common.utils.StringUtils;
import com.thwj.common.utils.poi.ExcelUtil;
import com.thwj.framework.mybatis_plus.GeoUtil;
import com.thwj.project.amap.dto.AppLocationDTO;
import com.thwj.project.app.service.AppAreaService;
import com.thwj.project.biz.controller.vo.MerchantVO;
import com.thwj.project.biz.domain.Merchant;
import com.thwj.project.biz.enums.MerchantTagEnum;
import com.thwj.project.biz.service.IMerchantService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 商家Controller
 *
 * @author generate
 * @date 2023-07-13
 */
@RestController
@RequestMapping("/biz/merchant")
public class MerchantController extends BaseController {
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    AppAreaService appAreaService;

/**
 * 查询商家列表
 */
@PreAuthorize("@ss.hasPermi('biz:merchant:list')")
@GetMapping("/list")
    public TableDataInfo list(Merchant merchant) {
        startPage();
        List<Merchant> list = merchantService.list(new QueryWrapper<>(merchant).orderByDesc("id"));
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('biz:merchant:list')")
    @GetMapping("/searchList")
    public AjaxResult searchList(Merchant merchant) {
        List<Merchant> list = merchantService.list(
                new QueryWrapper<Merchant>().like(!StringUtils.isEmpty(merchant.getName()),"name", merchant.getName())
        );
        return AjaxResult.success(list);
    }

    /**
     * 导出商家列表
     */
    @PreAuthorize("@ss.hasPermi('biz:merchant:export')")
    @Log(title = "商家", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Merchant merchant) {
        List<Merchant> list = merchantService.list(new QueryWrapper<>(merchant));
        ExcelUtil<Merchant> util = new ExcelUtil<Merchant>(Merchant. class);
        util.exportExcel(response, list, "商家数据");
    }

    /**
     * 获取商家详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:merchant:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        Merchant merchant = merchantService.getById(id);
        List<String> tagNameList = new ArrayList<>();
        // 读取标签
        if (merchant.getTagJson() != null) {
            String tagIdStr[] = merchant.getTagJson().split(",");
            for (int i = 0; i < tagIdStr.length; i++) {
                MerchantTagEnum merchantTagEnum = MerchantTagEnum.getMerchantTagEnumByValue(Integer.valueOf(tagIdStr[i]));
                if(merchantTagEnum!= null) {
                    tagNameList.add(merchantTagEnum.getName());
                }
            }
        }
        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        merchantVO.setTagNameList(String.join(",", tagNameList));
        return AjaxResult.success(merchantVO);
    }

    /**
     * 新增商家
     */
    @PreAuthorize("@ss.hasPermi('biz:merchant:add')")
    @Log(title = "商家", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Merchant merchant) {

        Merchant select = merchantService.getOne(
                new QueryWrapper<Merchant>()
                        .eq("user_id", merchant.getUserId())
        );
        if(select != null) {
            throw new ServiceException("选择的用户已存在商家，一个用户只能绑定一个商家");
        }

        if(!merchant.getLatitude().isNaN() && !merchant.getLongitude().isNaN()){
            // 补充经纬度换省市区
            String lngLat = merchant.getLongitude() + "," + merchant.getLatitude();
            AppLocationDTO appLocationDTO = appAreaService.getAppLocationVoByLngLat(lngLat);
            if(appLocationDTO == null) {
                throw new ServiceException("地址转换错误，请检查经纬度是否正确");
            }
            merchant.setLocation(GeoUtil.getWgs84Point(merchant.getLatitude(),merchant.getLongitude()));
            merchant.setCodeProv(appLocationDTO.getCodeProv());
            merchant.setCodeCity(appLocationDTO.getCodeCity());
            merchant.setNameCity(appLocationDTO.getNameCity());
            merchant.setNameProv(appLocationDTO.getNameProv());
            merchant.setCodeProv(appLocationDTO.getCodeProv());
            merchant.setCodeDistrict(appLocationDTO.getCodeDistrict());
            merchant.setNameDistrict(appLocationDTO.getNameDistrict());
        }

        return toAjax(merchantService.save(merchant));
    }

    /**
     * 修改商家
     */
    @PreAuthorize("@ss.hasPermi('biz:merchant:edit')")
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Merchant merchant) {
        if(!merchant.getLatitude().isNaN() && !merchant.getLongitude().isNaN()){
            // 补充经纬度换省市区
            String lngLat = merchant.getLongitude() + "," + merchant.getLatitude();
            AppLocationDTO appLocationDTO = appAreaService.getAppLocationVoByLngLat(lngLat);
            if(appLocationDTO == null) {
                throw new ServiceException("地址转换错误，请检查经纬度是否正确");
            }
            merchant.setLocation(GeoUtil.getWgs84Point(merchant.getLatitude(),merchant.getLongitude()));
            merchant.setCodeProv(appLocationDTO.getCodeProv());
            merchant.setCodeCity(appLocationDTO.getCodeCity());
            merchant.setNameCity(appLocationDTO.getNameCity());
            merchant.setNameProv(appLocationDTO.getNameProv());
            merchant.setCodeProv(appLocationDTO.getCodeProv());
            merchant.setCodeDistrict(appLocationDTO.getCodeDistrict());
            merchant.setNameDistrict(appLocationDTO.getNameDistrict());
        }
        return toAjax(merchantService.updateById(merchant));
    }

    /**
     * 删除商家
     */
    @PreAuthorize("@ss.hasPermi('biz:merchant:remove')")
    @Log(title = "商家", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(merchantService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 取消商家置顶
     */
    @PreAuthorize("@ss.hasPermi('biz:merchant:edit')")
    @Log(title = "取消商家置顶", businessType = BusinessType.UPDATE)
    @PostMapping("cancelTopMerchant")
    public AjaxResult cancelTopMerchant(@RequestParam Long id) {
        Merchant merchant = new Merchant();
        merchant.setId(id);
        merchant.setRecommendType(null);
        merchant.setRecommendIndex(null);
        return toAjax(merchantService.updateById(merchant));
    }


}
